{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Transformers installation\n",
    "! pip install transformers datasets evaluate accelerate\n",
    "# To install from source instead of the last release, comment the command above and uncomment the following one.\n",
    "# ! pip install git+https://github.com/huggingface/transformers.git"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Image Feature Extraction"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Image feature extraction is the task of extracting semantically meaningful features given an image. This has many use cases, including image similarity and image retrieval. Moreover, most computer vision models can be used for image feature extraction, where one can remove the task-specific head (image classification, object detection etc) and get the features. These features are very useful on a higher level: edge detection, corner detection and so on. They may also contain information about the real world (e.g. what a cat looks like) depending on how deep the model is. Therefore, these outputs can be used to train new classifiers on a specific dataset.\n",
    "\n",
    "In this guide, you will:\n",
    "\n",
    "- Learn to build a simple image similarity system on top of the `image-feature-extraction` pipeline.\n",
    "- Accomplish the same task with bare model inference."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Image Similarity using `image-feature-extraction` Pipeline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We have two images of cats sitting on top of fish nets, one of them is generated."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from PIL import Image\n",
    "import requests\n",
    "\n",
    "img_urls = [\"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png\", \"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.jpeg\"]\n",
    "image_real = Image.open(requests.get(img_urls[0], stream=True).raw).convert(\"RGB\")\n",
    "image_gen = Image.open(requests.get(img_urls[1], stream=True).raw).convert(\"RGB\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's see the pipeline in action. First, initialize the pipeline. If you don't pass any model to it, the pipeline will be automatically initialized with [google/vit-base-patch16-224](https://huggingface.co/docs/transformers/main/en/tasks/google/vit-base-patch16-224). If you'd like to calculate similarity, set `pool` to True."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from transformers import pipeline\n",
    "from accelerate import Accelerator\n",
    "# automatically detects the underlying device type (CUDA, CPU, XPU, MPS, etc.)\n",
    "device = Accelerator().device\n",
    "pipe = pipeline(task=\"image-feature-extraction\", model_name=\"google/vit-base-patch16-384\", device=DEVICE, pool=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To infer with `pipe` pass both images to it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "outputs = pipe([image_real, image_gen])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The output contains pooled embeddings of those two images."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# get the length of a single output\n",
    "print(len(outputs[0][0]))\n",
    "# show outputs\n",
    "print(outputs)\n",
    "\n",
    "# 768\n",
    "# [[[-0.03909236937761307, 0.43381670117378235, -0.06913255900144577,"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get the similarity score, we need to pass them to a similarity function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from torch.nn.functional import cosine_similarity\n",
    "\n",
    "similarity_score = cosine_similarity(torch.Tensor(outputs[0]),\n",
    "                                     torch.Tensor(outputs[1]), dim=1)\n",
    "\n",
    "print(similarity_score)\n",
    "\n",
    "# tensor([0.6043])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you want to get the last hidden states before pooling, avoid passing any value for the `pool` parameter, as it is set to `False` by default. These hidden states are useful for training new classifiers or models based on the features from the model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pipe = pipeline(task=\"image-feature-extraction\", model_name=\"google/vit-base-patch16-224\", device=DEVICE)\n",
    "outputs = pipe(image_real)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since the outputs are unpooled, we get the last hidden states where the first dimension is the batch size, and the last two are the embedding shape."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "print(np.array(outputs).shape)\n",
    "# (1, 197, 768)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Getting Features and Similarities using `AutoModel`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can also use `AutoModel` class of transformers to get the features. `AutoModel` loads any transformers model with no task-specific head, and we can use this to get the features."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoImageProcessor, AutoModel\n",
    "\n",
    "processor = AutoImageProcessor.from_pretrained(\"google/vit-base-patch16-224\")\n",
    "model = AutoModel.from_pretrained(\"google/vit-base-patch16-224\").to(DEVICE)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's write a simple function for inference. We will pass the inputs to the `processor` first and pass its outputs to the `model`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def infer(image):\n",
    "  inputs = processor(image, return_tensors=\"pt\").to(DEVICE)\n",
    "  outputs = model(**inputs)\n",
    "  return outputs.pooler_output"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can pass the images directly to this function and get the embeddings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "embed_real = infer(image_real)\n",
    "embed_gen = infer(image_gen)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can get the similarity again over the embeddings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from torch.nn.functional import cosine_similarity\n",
    "\n",
    "similarity_score = cosine_similarity(embed_real, embed_gen, dim=1)\n",
    "print(similarity_score)\n",
    "\n",
    "# tensor([0.6061], device='cuda:0', grad_fn=<SumBackward1>)"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 4
}
